//
//  SAInventoryWaterView.m
//  yidiantong
//
//  Created by 黄志刚 on 2020/11/4.
//

#import "SAInventoryWaterView.h"
#import "SAInventoryWaterCell.h"
#import "SAStockFlowListAPI.h"
#import "SAInventoryWaterModel.h"

@interface SAInventoryWaterView ()<UITableViewDataSource, UITableViewDelegate, HTTPAPIDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) SAStockFlowListAPI *stockFlowListAPI;
@property (nonatomic, strong) NSMutableArray <SAInventoryWaterList *>*dataMarr;
@property (nonatomic, strong) UILabel *stockLab;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, strong) UIView *tipView;
@property (nonatomic, strong) NSString *merchantId;

@end

@implementation SAInventoryWaterView

+(instancetype)shareCornView {
    SAInventoryWaterView * shareView = [[SAInventoryWaterView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    return shareView;
}

-(instancetype)initWithFrame:(CGRect)frame {
    if(self = [super initWithFrame:frame]) {
        self.userInteractionEnabled = YES;
        self.backgroundColor = kColor(0, 0, 0, 0.6);
        [self initUI];
    }
    return self;
}

-(void)loadData:(NSString *)productId MerchantId:(NSString *)merchantId Size:(NSString *)size Colour:(NSString *)colour {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *timeFormatStr = [dateFormatter stringFromDate:[NSDate date]];
    
    self.currentPage = 1;
    self.stockFlowListAPI.pageSize = 20;
    self.stockFlowListAPI.productId = productId;
    self.stockFlowListAPI.size = size;
    self.stockFlowListAPI.colour = colour;
    self.stockFlowListAPI.startTime = @"2000-01-01";
    self.stockFlowListAPI.endTime = timeFormatStr;
    self.stockFlowListAPI.merchantId = merchantId;
    [self refreshData];
}

-(void)refreshData {
    self.stockFlowListAPI.currentPage = self.currentPage;
    [self.stockFlowListAPI sendRequestToServerWithActivityViewAndMask:GET];
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
    
    if (self.stockFlowListAPI == api) {
        SAInventoryWaterModel *model = [SAInventoryWaterModel mj_objectWithKeyValues:data[@"data"]];
        self.stockLab.text = [NSString stringWithFormat:@"入库总量:%@  出库总量:%@",model.param.grandTotalSum,model.param.grandTotalLess];
        if (self.currentPage == 1) {
            self.dataMarr = model.records;
        }else {
            for (SAInventoryWaterList *watermodel in model.records) {
                [self.dataMarr addObject:watermodel];
            }
        }
        self.tipView.hidden = (self.dataMarr.count > 0);
        [self.tableView reloadData];
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}


#pragma mark - UITableView Delegate & DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataMarr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SAInventoryWaterCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SAInventoryWaterCell" forIndexPath:indexPath];
    cell.model = self.dataMarr[indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(45);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kScaleNum(0.01);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return kScaleNum(0.01);
}

#pragma mark - event


#pragma mark - initUI
-(void)initUI {
    UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteBtn.frame = CGRectMake(0, 0, kScreenWidth, kScaleNum(192));
    [deleteBtn addTarget:self action:@selector(shareDissTapEvent) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:deleteBtn];
    
    UIView *backGroundView = [[UIView alloc] initWithFrame:CGRectMake(0, kScaleNum(192), kScreenWidth, kScreenHeight - kScaleNum(192))];
    backGroundView.backgroundColor = kColor(246, 246, 246, 1);
    backGroundView.userInteractionEnabled = YES;
    [self addSubview:backGroundView];
    
    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    confirmBtn.frame = CGRectMake(kScreenWidth - kScaleNum(80), kScaleNum(0), kScaleNum(80), kScaleNum(40));
    [confirmBtn setTitle:@"关闭" forState:UIControlStateNormal];
    [confirmBtn setTitleColor:kBuleColor forState:UIControlStateNormal];
    [confirmBtn addTarget:self action:@selector(confirmationTapEvent) forControlEvents:UIControlEventTouchUpInside];
    [backGroundView addSubview:confirmBtn];
    
    UIView *whiteView = [[UIView alloc] initWithFrame:SARectMake(0, 40, kBaseScreenWidth, 40)];
    whiteView.backgroundColor = [UIColor whiteColor];
    [backGroundView addSubview:whiteView];
    
    UILabel *stockLab = [[UILabel alloc] initWithFrame:SARectMake(30, 40, 315, 40)];
    stockLab.textColor = kBlackColor;
    stockLab.font = kFont(15);
    stockLab.textAlignment = NSTextAlignmentLeft;
    [backGroundView addSubview:stockLab];
    self.stockLab = stockLab;
    
    UIImageView *imageV = [[UIImageView alloc] initWithFrame:SARectMake(0, 80, kBaseScreenWidth, 40)];
    imageV.backgroundColor = kTextBgColor;
    [backGroundView addSubview:imageV];
    NSArray *arr = @[@"操作类型", @"颜色/尺码", @"入库", @"出库"];
    NSArray *arr2 = @[@"30", @"130", @"230", @"300"];
    NSArray *arr3 = @[@"100", @"100", @"70", @"70"];
    for (int i = 0; i < arr.count; i++) {
        NSInteger x = [arr2[i] integerValue];
        NSInteger w = [arr3[i] integerValue];
        UILabel *titleLab = [[UILabel alloc] initWithFrame:SARectMake(x, 0, w, 40)];
        titleLab.text = arr[i];
        titleLab.textColor = kTextColor;
        titleLab.font = kFont(15);
        if (i > 1) {
            titleLab.textAlignment = NSTextAlignmentCenter;
        }else{
            titleLab.textAlignment = NSTextAlignmentLeft;
        }
        [imageV addSubview:titleLab];
    }
    
    [backGroundView addSubview:self.tableView];
    [backGroundView addSubview:self.tipView];
    WeakSelf
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf endEditing:YES];
        weakSelf.currentPage = 1;
         [weakSelf refreshData];
     }];
    MJRefreshAutoStateFooter *mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        [weakSelf endEditing:YES];
        weakSelf.currentPage ++;
        [weakSelf refreshData];
    }];
    [mj_footer setTitle:@"已经到底啦~" forState:MJRefreshStateIdle];//设置闲置状态下不显示“点击或上拉加载更多”
    self.tableView.mj_footer = mj_footer;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kScaleNum(120), kScreenWidth,kScreenHeight - kScaleNum(312)) style:UITableViewStylePlain];
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
        _tableView.backgroundColor = kLineColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [_tableView registerClass:[SAInventoryWaterCell class] forCellReuseIdentifier:@"SAInventoryWaterCell"];
    }
    return _tableView;
}

- (void)showView:(UIViewController *)Sview {
    if(Sview == nil){
        [[UIApplication sharedApplication].keyWindow addSubview:self];
    }else{
        [Sview.view addSubview:self];
    }
}

-(void)shareDissTapEvent {
    [UIView animateWithDuration:0.5f animations:^{
        self.alpha = 0.0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

-(void)confirmationTapEvent {
    [UIView animateWithDuration:0.5f animations:^{
        
        self.alpha = 0.0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self endEditing:YES];
}

-(SAStockFlowListAPI *)stockFlowListAPI {
    if (!_stockFlowListAPI) {
        _stockFlowListAPI = [SAStockFlowListAPI apiWithDelegate:self];
    }
    return _stockFlowListAPI;
}

-(NSMutableArray<SAInventoryWaterList *> *)dataMarr {
    if (!_dataMarr) {
        _dataMarr = [NSMutableArray array];
    }
    return _dataMarr;
}

-(UIView *)tipView {
    if (!_tipView) {
        _tipView = [[UIView alloc] initWithFrame:CGRectMake(0, kScaleNum(120), kScreenWidth,kScreenHeight - kScaleNum(312))];
        _tipView.backgroundColor = kLineColor;
        UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Shop_search2"]];
        icon.frame = SARectMake(124, 147 - StatusHeight, 138, 83);
        [_tipView addSubview:icon];
        UILabel *titleLab = [[UILabel alloc] initWithFrame:SARectMake(0, 240 - StatusHeight, kBaseScreenWidth, 30)];
        titleLab.text = @"暂无相关信息";
        titleLab.textAlignment = NSTextAlignmentCenter;
        titleLab.textColor = kGrayColor;
        [_tipView addSubview:titleLab];
    }
    return _tipView;
}

@end
